package com.oneplus;

import com.oneplus.entitys.NodeAddress;
import com.oneplus.interfaces.utils.PropertyUtil;
import com.oneplus.network.core.*;
import com.oneplus.network.ehcacheManager.InitializationManager;
import com.oneplus.network.ehcacheManager.NioSocketChannelManager;
import com.oneplus.network.ehcacheManager.SyncBlockManager;
import com.oneplus.repositorys.NodeAddressRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.math.BigInteger;

/**
 * OnePlus BlockChain Service!
 *
 */
@SpringBootApplication
@EnableCaching
public class App implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private GenesisBlock genesisBlock;
    @Autowired
    private NodeAddressRepository nodeAddressRepository;
    @Autowired
    private CheckPoint checkPoint;
    @Autowired
    private InitializationManager initializationManager;
    @Autowired
    private ResetData resetData;
    @Autowired
    private NioSocketChannelManager nioSocketChannelManager;
    @Autowired
    private SyncBlockManager syncBlockManager;

    public static void main( String[] args )
    {
        SpringApplicationBuilder builder = new SpringApplicationBuilder(App.class);
        builder.headless(false).run(args);
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        genesisBlock.init ( );
        try {
            Thread.sleep ( 10000 );
        } catch (InterruptedException e) {
            e.printStackTrace ( );
        }
        checkPoint.checkDate ( );
        if ( nioSocketChannelManager.getActiveNioSocketChannelCount ( ) >= BigInteger.ONE.longValue ( ) && initializationManager.getBlockHeight ( ) > 2 ) {
            syncBlockManager.setSyncBlock ( true );
            resetData.backBlock ( 2 );
        }
    }

}
